<template>
  <doc-alert title="【产品】产品信息、分类、单位" url="https://doc.iocoder.cn/erp/product/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryList"
          :props="defaultProps"
          default-expand-all
          placeholder="请输入分类"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:product:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <!-- 批量设置直入直出按钮 -->
        <el-button
          type="primary"
          plain
          @click="openDirectForm"
          :loading="directLoading"
          v-hasPermi="['erp:product:update']"
        >
          <Icon icon="ep:edit" class="mr-5px" /> 批量设置直入直出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <el-table-column type="selection" width="55" />
      <el-table-column label="条码" align="center" prop="barCode" />
      <el-table-column label="名称" align="center" prop="name" min-width="180" />
      <el-table-column label="产品规格" align="center" prop="standard" />
      <el-table-column label="一级分类" align="center" prop="parentCategoryName" />
      <el-table-column label="二级分类" align="center" prop="categoryName" />
      <el-table-column label="计量单位" align="center" prop="unitName" />
      <el-table-column label="单件重量(g)" align="center" prop="weight" />
      <el-table-column
        label="采购价格"
        align="center"
        prop="purchasePrice"
        :formatter="erpPriceTableColumnFormatter"
      />
      <el-table-column
        label="最低价格"
        align="center"
        prop="minPrice"
        :formatter="erpPriceTableColumnFormatter"
      />
      <!--      <el-table-column label="状态" align="center" prop="status">-->
      <!--        <template #default="scope">-->
      <!--          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="是否直入直出" align="center" prop="productType" min-width="140">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INSERT_OR_OUT" :value="scope.row.productType" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="110" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:product:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:product:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="formRef" @success="getList" />

  <!-- 批量设置直入直出弹窗（整合到当前页面） -->
  <el-dialog
    v-model="directVisible"
    title="批量设置直入直出"
    width="500px"
    :close-on-click-modal="false"
    @close="handleDirectClose"
  >
    <el-form
      ref="directFormRef"
      :model="directForm"
      :rules="directRules"
      label-width="120px"
      class="space-y-4"
    >
      <!-- 直入直出状态 -->
      <el-form-item label="直入直出状态" prop="productType">
        <el-select
          v-model="directForm.productType"
          placeholder="请选择状态"
          clearable
          style="width: 100%"
          :disabled="dictLoading"
        >
          <el-option
            v-for="item in dictOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleDirectClose">取消</el-button>
      <el-button type="primary" @click="handleDirectSubmit" :loading="submitLoading"
        >确认提交</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProductApi, ProductVO, ProductUpdateDirectReqVO } from '@/api/erp/product/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import ProductForm from './ProductForm.vue'
import { DICT_TYPE, getIntDictOptions, NumberDictDataType } from '@/utils/dict'
import { defaultProps, findPath, handleTree } from '@/utils/tree'
import { erpPriceTableColumnFormatter } from '@/utils'

/** ERP 产品列表 */
defineOptions({ name: 'ErpProduct' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 列表基础数据
const loading = ref(true)
const list = ref<ProductVO[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  categoryId: undefined,
  parentCategoryId: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)
const categoryList = ref<ProductCategoryVO[]>([])

// 批量操作相关（整合弹窗逻辑）
const selectedIds = ref<number[]>([]) // 选中的产品ID
const directVisible = ref(false) // 弹窗显示状态
const directFormRef = ref<InstanceType<typeof ElForm>>()
const dictOptions = ref<NumberDictDataType[]>([]) // 直入直出字典选项
const dictLoading = ref(false) // 字典加载状态
const submitLoading = ref(false) // 提交加载状态
const directLoading = ref(false) // 按钮加载状态

// 批量设置表单数据
const directForm = reactive<ProductUpdateDirectReqVO>({
  ids: [],
  productType: undefined
})

// 批量设置表单规则
const directRules = reactive<Record<string, ElFormItemRule[]>>({
  productType: [{ required: true, message: '请选择直入直出状态', trigger: 'change' }]
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  const params = { ...queryParams }
  if (params.categoryId) {
    const categoryNodes = findPath(categoryList.value, (elem) => elem.id == params.categoryId)
    if (categoryNodes.length == 1) {
      params.parentCategoryId = categoryNodes[0].id
      params.categoryId = undefined
    }
  }
  try {
    const data = await ProductApi.getProductPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索/重置/新增/删除/导出 方法保持不变 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await ProductApi.deleteProduct(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const params = { ...queryParams }
    if (params.categoryId) {
      const categoryNodes = findPath(categoryList.value, (elem) => elem.id == params.categoryId)
      if (categoryNodes.length == 1) {
        params.parentCategoryId = categoryNodes[0].id
        params.categoryId = undefined
      }
    }
    const data = await ProductApi.exportProduct(params)
    download.excel(data, '物料.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 批量操作相关方法 */
// 收集选中的ID
const handleSelectionChange = (val: ProductVO[]) => {
  selectedIds.value = val.map((item) => item.id)
}

// 加载直入直出字典
const loadDict = async () => {
  if (dictOptions.value.length > 0) return
  dictLoading.value = true
  try {
    dictOptions.value = getIntDictOptions(DICT_TYPE.INSERT_OR_OUT, true)
  } catch (error) {
    ElMessage.error('字典加载失败，请刷新页面重试')
    console.error('字典加载错误：', error)
  } finally {
    dictLoading.value = false
  }
}

// 打开批量设置弹窗
const openDirectForm = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择需要操作的产品')
    return
  }
  directLoading.value = true
  try {
    // 初始化表单
    directForm.ids = [...selectedIds.value]
    directForm.productType = undefined
    // 加载字典
    loadDict().then(() => {
      directVisible.value = true
    })
  } finally {
    directLoading.value = false
  }
}

// 关闭弹窗
const handleDirectClose = () => {
  directVisible.value = false
  directFormRef.value?.resetFields()
  submitLoading.value = false
}

// 提交批量设置
const handleDirectSubmit = async () => {
  try {
    await directFormRef.value?.validate()
    submitLoading.value = true
    await ProductApi.updateDirectType(directForm)
    ElMessage.success('批量设置成功')
    handleDirectClose()
    getList() // 刷新列表
    selectedIds.value = [] // 清空选中状态
  } catch (error) {
    // 忽略校验和接口错误（已有默认提示）
  } finally {
    submitLoading.value = false
  }
}

/** 初始化 */
onMounted(async () => {
  await getList()
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
})
</script>
